Ext.define('Admin.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main',

    listen : {
        controller : {
            '#' : {
                unmatchedroute : 'onRouteChange'
            }
        }
    },

    routes: {
        ':node': 'onRouteChange',
        //c4w
        '(:en)detail/:id':{
            action     : 'showDetail'
        }
    },
    config: {
        //c4w
        control: {
            'ETasklist':{
            	openobj:'onOpenObj',
            	//editobj:'onEditObj'
            },
            'ETaskdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
            'Userlist':{
            	openobj:'onOpenObj',
            },
            'Userdetail':{
            	objnext:'objNext',
            	objprev:'objPrev'
            },
       }

    },

    lastView: null,
    //c4w
    showLogin:function(){
    	if(this.login)
			return;
		this.login = new DCApp.view.login.Login({
			session: this.session,
			autoShow: true,
			listeners: {
				scope: this,
				login: 'onLogin'
			}
        });
    },
    objNext:function(){    	
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_next;
     	var pos = ds.indexOf(rec);
     	inf.rec_prev= inf.rec;
     	inf.rec=inf.rec_next;
     	inf.rec_next = ds.getAt(pos+1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    objPrev:function(){
    	var inf = this.open_info;    	
     	var ds = inf.list.getStore();
     	var rec=inf.rec_prev;
     	var pos = ds.indexOf(rec);
     	inf.rec_next= inf.rec;
     	inf.rec=inf.rec_prev;
     	inf.rec_prev = ds.getAt(pos-1);
    	this.redirectTo(inf.nd + '/'+ rec.id);
    },
    
    viewObj:function(rec,id,detail_type,pinf){
        var inf = pinf ||{};
        var data = {
            theObj: rec,
            showprev:Boolean(inf.rec_prev),
            shownext:Boolean(inf.rec_next),
            showsave:true,
            showreturn:inf.true
        };
        var vm = {
            data: data
        };

        var me = this,
        refs = me.getReferences(),
        mainCard = refs.mainCardPanel,
        mainLayout = mainCard.getLayout(),
        view = detail_type,
        lastView = me.lastView,
        existingItem = mainCard.child('component[routeId=' + detail_type + ']'),
        newView;

    // Kill any previously routed window
    if (lastView && lastView.isWindow) {
        lastView.destroy();
    }

    lastView = mainLayout.getActiveItem();

    if (!existingItem) {
        newView = Ext.create({
            xtype: detail_type,
            routeId: detail_type,  // for existingItem search later
            hideMode: 'offsets',
            viewModel:vm
        });
    }else{
        existingItem.getViewModel().setData(data);      
    } 

    if (!newView || !newView.isWindow) {
        // !newView means we have an existing view, but if the newView isWindow
        // we don't add it to the card layout.
        if (existingItem) {
            // We don't have a newView, so activate the existing view.
            if (existingItem !== lastView) {
                mainLayout.setActiveItem(existingItem);
            }
            newView = existingItem;
        }
        else {
            // newView is set (did not exist already), so add it and make it the
            // activeItem.
            Ext.suspendLayouts();
            mainLayout.setActiveItem(mainCard.add(newView));
            Ext.resumeLayouts(true);
        }
    }

    if (newView.isFocusable(true)) {
        newView.focus();
    }

    me.lastView = newView;
    
  },

    showDetail:function(p1,p2,p3){
		//console.log('showDetail:'+p1+":"+p3);
        var me=this;
        var pinf = me.open_info;
		if(pinf){   
            //TODO 向前/向后/返回／保存        
			return me.viewObj(pinf.rec,p3,pinf.nd,pinf);
		}
        var pdetail = p1+'detail';
        //TODO with login
		if(false && !Admin.Cfg.usrInfo){
			me.setOrigUri(pdetail+'/'+p3);
			return me.showLogin();
		}
		var className = 'Admin.model.'+Ext.String.capitalize(p1);
    	var modelClass = Ext.ClassManager.get(className);
    	//不符合detail命名规则的走VIP通道
    	if(!modelClass){
    		modelClass=Ext.ClassManager.get('Admin.model.'+detailCMap[p1]);
    	}
    	if(!modelClass)
    		return false;
    	var pm={};
    	pm[modelClass.idProperty||'id']=parseInt(p3);
    	var obj = modelClass.create(pm);
    	var me=this;
    	//Uses the configured RestProxy to make a GET request to /users/123
    	obj.load({
    		scope: this,
    	    success: function(rec) {
    	        me.viewObj(rec,p3,pdetail);
    	    }
    	});
    	
    },
    onOpenObj:function(vw,rec,action){
    	//var vm = vw.getViewModel();
    	//var nd = this.getView().getXType().replace('detail','list');
    	var nl = vw.xtype;
     	var nd = nl.replace('list','detail');
     	var ds = vw.getStore();
     	var pos = ds.indexOf(rec);
     	if(pos==-1){
     		rec.set('id',-1);
     	}     	
     	this.open_info={
     		list:vw,
     		rec:rec,
     		nd:nd,nl:nl,
     		rec_prev : ds.getAt(pos-1),
     		rec_next : ds.getAt(pos+1),
     		scroll_y : vw.getScrollY(),
     		action:action
     	};
    	this.redirectTo(nd + '/'+ rec.id);
    },
    
    //c4w end

    setCurrentView: function(hashTag) {
        hashTag = (hashTag || '').toLowerCase();

        var me = this,
            refs = me.getReferences(),
            mainCard = refs.mainCardPanel,
            mainLayout = mainCard.getLayout(),
            navigationList = refs.navigationTreeList,
            store = navigationList.getStore(),
            node = store.findNode('routeId', hashTag) ||
                   store.findNode('viewType', hashTag),
            view = (node && node.get('viewType')) || 'page404',
            lastView = me.lastView,
            existingItem = mainCard.child('component[routeId=' + hashTag + ']'),
            newView;

        // Kill any previously routed window
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();

        if (!existingItem) {
            newView = Ext.create({
                xtype: view,
                routeId: hashTag,  // for existingItem search later
                hideMode: 'offsets'
            });
        }

        if (!newView || !newView.isWindow) {
            // !newView means we have an existing view, but if the newView isWindow
            // we don't add it to the card layout.
            if (existingItem) {
                // We don't have a newView, so activate the existing view.
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            }
            else {
                // newView is set (did not exist already), so add it and make it the
                // activeItem.
                Ext.suspendLayouts();
                mainLayout.setActiveItem(mainCard.add(newView));
                Ext.resumeLayouts(true);
            }
        }

        navigationList.setSelection(node);

        if (newView.isFocusable(true)) {
            newView.focus();
        }

        me.lastView = newView;
    },

    onNavigationTreeSelectionChange: function (tree, node) {
        var to = node && (node.get('routeId') || node.get('viewType'));

        if (to) {
            this.redirectTo(to);
        }
    },

    onToggleNavigationSize: function () {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList,
            wrapContainer = refs.mainContainerWrap,
            collapsing = !navigationList.getMicro(),
            new_width = collapsing ? 64 : 250;

        if (Ext.isIE9m || !Ext.os.is.Desktop) {
            Ext.suspendLayouts();

            refs.senchaLogo.setWidth(new_width);

            navigationList.setWidth(new_width);
            navigationList.setMicro(collapsing);

            Ext.resumeLayouts(); // do not flush the layout here...

            // No animation for IE9 or lower...
            wrapContainer.layout.animatePolicy = wrapContainer.layout.animate = null;
            wrapContainer.updateLayout();  // ... since this will flush them
        }
        else {
            if (!collapsing) {
                // If we are leaving micro mode (expanding), we do that first so that the
                // text of the items in the navlist will be revealed by the animation.
                navigationList.setMicro(false);
            }
            navigationList.canMeasure = false;

            // Start this layout first since it does not require a layout
            refs.senchaLogo.animate({dynamic: true, to: {width: new_width}});

            // Directly adjust the width config and then run the main wrap container layout
            // as the root layout (it and its chidren). This will cause the adjusted size to
            // be flushed to the element and animate to that new size.
            navigationList.width = new_width;
            wrapContainer.updateLayout({isRoot: true});
            navigationList.el.addCls('nav-tree-animating');

            // We need to switch to micro mode on the navlist *after* the animation (this
            // allows the "sweep" to leave the item text in place until it is no longer
            // visible.
            if (collapsing) {
                navigationList.on({
                    afterlayoutanimation: function () {
                        navigationList.setMicro(true);
                        navigationList.el.removeCls('nav-tree-animating');
                        navigationList.canMeasure = true;
                    },
                    single: true
                });
            }
        }
    },

    onMainViewRender:function() {
        if (!window.location.hash) {
            this.redirectTo("dashboard");
        }
    },

    onRouteChange:function(id){
        this.setCurrentView(id);
    },

    onSearchRouteChange: function () {
        this.setCurrentView('searchresults');
    },

    onSwitchToModern: function () {
        Ext.Msg.confirm('Switch to Modern', 'Are you sure you want to switch toolkits?',
                        this.onSwitchToModernConfirmed, this);
    },

    onSwitchToModernConfirmed: function (choice) {
        if (choice === 'yes') {
            var s = window.location.search;

            // Strip "?classic" or "&classic" with optionally more "&foo" tokens
            // following and ensure we don't start with "?".
            s = s.replace(/(^\?|&)classic($|&)/, '').replace(/^\?/, '');

            // Add "?modern&" before the remaining tokens and strip & if there are
            // none.
            window.location.search = ('?modern&' + s).replace(/&$/, '');
        }
    },

    onEmailRouteChange: function () {
        this.setCurrentView('email');
    }
});
